package LeetCode.leetcode111;


import java.util.LinkedList;
import java.util.Queue;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null)
            return 0;
        int res = 0;
        TreeNode tmp;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            res += 1;
            int size = queue.size();
            while (size > 0) {
                tmp = queue.poll();
                if (tmp.left == null && tmp.right == null) {
                    return res;
                }
                if (tmp.left != null)
                    queue.offer(tmp.left);
                if (tmp.right != null)
                    queue.offer(tmp.right);

                size--;
            }
        }
        return res;
    }
}
